//
//  LastestGoodsVC.m
//  夺宝吧
//
//  Created by xiaocai on 15/6/15.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "LastestGoodsVC.h"
#import "LastestWaitCell.h"
#import "LastestResCell.h"
#import "LatestCellModel.h"
#import "MJRefresh.h"
#import "PdcDetailVC.h"
#import "NoDataView.h"
//static LastestGoodsVC *_lastestGoodsVC=nil;

@interface LastestGoodsVC ()<UITableViewDataSource,UITableViewDelegate>
{
    
    NSInteger _currentPage;
    
}
@end

@implementation LastestGoodsVC
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //每一次出现时超过30秒刷新
    NSDate *dateNow = [NSDate date];
    NSTimeInterval nowTime = [dateNow timeIntervalSince1970];
    NSLog(@"%f %f",nowTime,nowTime-self.lastFreshDate);
    if ((nowTime - self.lastFreshDate)> TIMER_COUNT ){
        [self timerUpdate];
    }

    //自动刷新(一进入程序就下拉刷新)
    if (self.firstFlag || (self.data.count == 0) ) {
        [self headerRereshing];
    }
    self.firstFlag = NO;
}
//获取最新揭晓商品界面的单例
+ (LastestGoodsVC *)shareLastestGoodsVC
{
    static LastestGoodsVC *staticLastGoodsVC = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        staticLastGoodsVC = [[LastestGoodsVC alloc]init];
        
    });
    return staticLastGoodsVC;
}
- (void)timerUpdate{
    
    //记录最后刷新的时间
    NSDate *dateNow = [NSDate date];
    self.lastFreshDate = [dateNow timeIntervalSince1970];
    
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    [self headerRereshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //出事化当前时间
    NSDate *dateNow = [NSDate date];
    self.lastFreshDate =  [dateNow timeIntervalSince1970];
    //初始化计时器
//    self.timer = [NSTimer timerWithTimeInterval:TIMER_COUNT target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    self.freshCount = 0;
    
    self.firstFlag = YES;
    // Do any additional setup after loading the view.
    _currentPage = 1;
    _data = [NSMutableArray array];
    //加载导航条
    [self loadCustomNaviBar];
    //加载列表
    [self loadtableView];
}
//加载导航条
- (void)loadCustomNaviBar
{
    UIView *naviBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WYMWITH, 20+44)];
    naviBar.backgroundColor = QBB_RED_COLOR;

    //标题
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 25)];
    titleLab.center = CGPointMake(WYMWITH/2, 42);
    titleLab.text = @"最新揭晓";
    titleLab.font = [UIFont systemFontOfSize:TITLE_SIZE];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = [UIColor whiteColor];
    [naviBar addSubview:titleLab];
    [self.view addSubview:naviBar];
}


//加载tableview
- (void)loadtableView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44 + 20, WYMWITH, WYMHEIGHT-20-44-49)];
    _tableView.dataSource =self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //注册cell
    UINib *nib1 = [UINib nibWithNibName:@"LastestWaitCell" bundle:nil];
    UINib *nib2 = [UINib nibWithNibName:@"LastestResCell" bundle:nil];
    [_tableView registerNib:nib1 forCellReuseIdentifier:@"cell1"];
    [_tableView registerNib:nib2 forCellReuseIdentifier:@"cell2"];
    _tableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tableView];
    [self setupRefresh];
//    [self startRequestForNew];
//    [self headerRereshing];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    //    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // dateKey用于存储刷新时间，可以保证不同界面拥有不同的刷新时间
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    _currentPage = 1;
    self.isPullDownFresh = YES;
//    [_data removeAllObjects];
    [self startRequestForNew];
}

- (void)footerRereshing
{
    self.isPullUpFresh = YES;
    _currentPage++;
    [self startRequestForNew];
}
//刷新界面  时间到的时候开奖的请求接口
- (void)reloadVCIndex:(NSInteger)index
{
    if (index<_data.count) {
        LatestCellModel *indexModel = _data[index];
        if (indexModel.pdc_id != nil ) {
//            && [indexModel.pdc_id isKindOfClass:[NSNull class]] && indexModel.pdc_id.length != 0
            
            double delayInSeconds = arc4random_uniform(3) + 1;
        __block LastestGoodsVC* bself = self;
        __block NSInteger bindex = index;
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            
            //新接口
            NSDictionary *params = @{@"id":indexModel.pdc_id,@"get_go_total":@1};
            [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,DETAIL_URL_NEW] Parameters:params successBlock:^(NSDictionary *dic) {
                //刷新单个cell成功后的数据
                NSDictionary *pdc = dic[@"data"];
                
                indexModel.pdc_owner_name = pdc[@"q_username"];
                indexModel.pdc_owner_code = pdc[@"q_user_code"];
                
                if([indexModel.pdc_owner_name class] == [NSNull class] || (indexModel.pdc_owner_name == nil)){
                    NSString *dicStr = [NSString stringWithFormat:@"dic: %@",dic];
//                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"测试" message:dicStr delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//                    [alertView show];
                    self.freshCount += 1;
                    if (self.freshCount < 4){
                        [self reloadVCIndex:index];
                    }
                    return;
                }
                if([indexModel.pdc_owner_code class] == [NSNull class] || (indexModel.pdc_owner_code == nil)){
                    NSString *dicStr = [NSString stringWithFormat:@"dic: %@",dic];
//                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"测试" message:dicStr delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//                    [alertView show];
                    self.freshCount += 1;
                    if (self.freshCount < 4){
                        [self reloadVCIndex:index];
                    }
                    return;
                }
                self.freshCount = 0;
                indexModel.pdc_id = pdc[@"id"];
                indexModel.pdc_sid = pdc[@"sid"];
                indexModel.pdc_owner_id = pdc[@"q_uid"];
                
                indexModel.pdc_end_time = pdc[@"q_end_time"];
                NSNumber *t_n = pdc[@"go_total"];
                indexModel.pdc_owner_totle = [t_n integerValue];
                indexModel.pdc_open_time_flag = @"N";
                indexModel.pdc_real_time = 0;
                
                //            indexModel
                //            NSNumber *time_n = pdc[@"countdown"];
                //            indexModel.pdc_time_count = [time_n integerValue];
                //            indexModel.pdc_title = pdc[@"title"];
                indexModel.pdc_time_count = [NSNumber numberWithInteger:0];
                
                if (index < _data.count) {
                    //一个cell刷新
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:index inSection:0];
                    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                }
                
                // [_tableView reloadData];
                
            } failedBlock:^{
                
                NSLog(DETAIL_URL_NEW);
                NSLog(NSSTRING_PRETTY_FUNCTION);
                
            } needLog:NO];

        });
        }
        
    }

}
/***********
 *加载最新揭晓列表
 ****************/
- (void)startRequestForNew
{
    [WYPublic addHudToWindow];
    NSDictionary *params = @{@"num":@"20",@"page":[NSString stringWithFormat:@"%ld",(unsigned long)_currentPage]};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,NEW_PUBLISH_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        @synchronized(self) {
            NSNumber *ret = dic[@"ret"];
            if ([ret intValue] == 0) {
                NSArray *pdcs = dic[@"data"];
                //循环向data中添加数据
                if (self.isPullDownFresh){
                    [_data removeAllObjects];
                    self.isPullDownFresh = NO;
                    [self _convertDict:pdcs];
                }
                if (self.isPullUpFresh){
                    self.isPullUpFresh = NO;
                    [self _convertDict:pdcs];
                }
                
            }else{
                
                if(_data.count == 0){
                    for (UIView *v in _tableView.subviews) {
                        if (v.tag == 12121) {
                            [v removeFromSuperview];
                        }
                    }
                    [self addNODataView];
                }
                [_tableView headerEndRefreshing];
                [_tableView footerEndRefreshing];
                [WYPublic removeHudToWindow];
            }

        }
        
        
    } failedBlock:^{
        if(_data.count > 0){
            //一处NoDataView NoDataView的tag是 12121
            for (UIView *v in _tableView.subviews) {
                if (v.tag == 12121) {
                    [v removeFromSuperview];
                }
            }
        }else{
            for (UIView *v in _tableView.subviews) {
                if (v.tag == 12121) {
                    [v removeFromSuperview];
                }
            }
            [self addNODataView];
        }
        [_tableView headerEndRefreshing];
        [_tableView footerEndRefreshing];
        [WYPublic removeHudToWindow];
    } needLog:NO];
}
- (void)_convertDict:(NSArray *)pdcs {
    
    for (NSDictionary *pdc in pdcs) {
        LatestCellModel *model = [[LatestCellModel alloc]init];
        model.pdc_desc =pdc[@"description"];
        model.pdc_end_time = pdc[@"q_end_time"];
        model.pdc_id = pdc[@"id"];
        model.pdc_img_url = pdc[@"thumb_url"];
        model.pdc_open_time_flag = pdc[@"q_showtime"];
        model.pdc_owner_code = pdc[@"q_user_code"];
        model.pdc_owner_id = pdc[@"q_uid"];
        model.pdc_owner_name = pdc[@"q_username"];
        NSNumber *t_n = pdc[@"go_total"];
        model.pdc_owner_totle = [t_n integerValue];
        model.pdc_qishu = pdc[@"qishu"];
        model.pdc_sid = pdc[@"sid"];
        model.pdc_sub_title = pdc[@"title2"];
        NSNumber *time_n = pdc[@"countdown"];
        model.pdc_time_count = [time_n integerValue];
        model.pdc_title = pdc[@"title"];
        
        [_data addObject:model];
    }
    
    
    if(_data.count > 0){
        for (UIView *v in _tableView.subviews) {
            if (v.tag == 12121) {
                [v removeFromSuperview];
            }
        }
        [_tableView reloadData];
    }
    else{
        
        if(_data.count == 0){
            for (UIView *v in _tableView.subviews) {
                if (v.tag == 12121) {
                    [v removeFromSuperview];
                }
            }
            [self addNODataView];
        }
    }
    
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [WYPublic removeHudToWindow];
    
}

//没有数据默认填充的控件
- (void)addNODataView{
    NoDataView *nodateView = [[[NSBundle mainBundle]loadNibNamed:@"NoDataView" owner:self options:nil]lastObject];
    nodateView.tag = 12121;
    nodateView.frame = CGRectMake(0, 0, WYMWITH, _tableView.contentSize.height);
    nodateView.isMineFlag = NO;
    nodateView.title = @"获取数据失败!";
    [_tableView addSubview:nodateView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (_data.count>0) {
//        LatestCellModel *model = _data[indexPath.row];
//        if ([model.pdc_open_time_flag isEqualToString:@"Y"]) {
//            return 110;
//        }
//    }
    return 110;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_data.count > 0)
    {
        LatestCellModel *model = _data[indexPath.row];
        if ([model.pdc_open_time_flag isEqualToString:@"N"]) {
            LastestResCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell fillCellWhithModel:model];
            NSLog(@"LastestResCell: %p",cell);
            return cell;
        }else{
            LastestWaitCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
            cell.father = self;
            [cell fillCellWhithModel:model Index:indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSLog(@"LastestWaitCell: %p",cell);
            return cell;
        }
    }
    UITableViewCell *cell = [[UITableViewCell alloc]init];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //保存至兴趣记录
    if (_data.count > 0) {
        LatestCellModel *currentModel = _data[indexPath.row];
        WYShopCarModel *model = [[WYShopCarModel alloc]init];
        model.car_id = currentModel.pdc_id;
        model.car_new_id = currentModel.pdc_sid;
        model.name = currentModel.pdc_title;
        model.imgPath = currentModel.pdc_img_url;
        model.count = 1;
        [[WYDataBase sharedDataBase]insertPdcToIntrestCarWithModel:model];
        
        //跳往商品详情
        PdcDetailVC *detailVC = [[PdcDetailVC alloc]init];
        detailVC.pdc_id = currentModel.pdc_id;
        [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:detailVC animated:YES];
        self.firstFlag = NO;
    }
   
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
//    [WYPublic removeHudToWindow];
    //停止请求
//    [WYRequest stopAllRequest];
//    // 结束刷新
//    [_tableView headerEndRefreshing];
//    [_tableView footerEndRefreshing];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end
